//
// 
// 给你两棵二叉树 root 和 subRoot 。检验 root 中是否包含和 subRoot 具有相同结构和节点值的子树。如果存在，返回 true ；否则
//，返回 false 。 
//
// 二叉树 tree 的一棵子树包括 tree 的某个节点和这个节点的所有后代节点。tree 也可以看做它自身的一棵子树。 
//
// 
//
// 示例 1： 
//
// 
//输入：root = [3,4,5,1,2], subRoot = [4,1,2]
//输出：true
// 
//
// 示例 2： 
//
// 
//输入：root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
//输出：false
// 
//
// 
//
// 提示： 
//
// 
// root 树上的节点数量范围是 [1, 2000] 
// subRoot 树上的节点数量范围是 [1, 1000] 
// -104 <= root.val <= 104 
// -104 <= subRoot.val <= 104 
// 
// 
// 
// Related Topics 树 深度优先搜索 二叉树 字符串匹配 哈希函数 
// 👍 580 👎 0

package com.cute.leetcode.editor.cn;
public class SubtreeOfAnotherTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        TreeNode t1node1 = new TreeNode(4);
        TreeNode t1node2 = new TreeNode(5);
        TreeNode t1node3 = new TreeNode(1);
        TreeNode t1node4 = new TreeNode(2);
        root.left = t1node1;root.right = t1node2;t1node1.left = t1node3;t1node1.right = t1node4;

        TreeNode subRoot = new TreeNode(4);
        TreeNode t2node1 = new TreeNode(1);
        TreeNode t2node2 = new TreeNode(2);
        subRoot.left = t2node1;subRoot.right = t2node2;

        boolean res = new SubtreeOfAnotherTree().new Solution().isSubtree(root, subRoot);


    }
    public static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (subRoot == null) return true;//如果子树是空的，直接返回true
        if (root == null) return false;//此时子树不为空，如果root是空直接返回false
        //接下来，判断左子树与subRoot是否匹配，右子树与subRoot是否匹配，当前树与subRoot是否一样
        return isSubtree(root.left,subRoot) || isSubtree(root.right, subRoot) || isSame(root,subRoot);

    }

    /**
     * 遍历两棵树是否相等还是不复杂的代码
     */
    public boolean isSame(TreeNode root, TreeNode subRoot){
        if (root == null && subRoot == null) return true;
        if (root == null || subRoot == null) return false;
        if (root.val != subRoot.val) return false;
        return isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

}